#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <pthread.h>

#define PORT 10086

// 用于存储通信的套接字
int client_socket;

// 用于接收客户端消息的线程函数
void* receiveMessages(void* arg) {
    char buffer[1024];
    while (1) {
        int valread = recv(client_socket, buffer, sizeof(buffer), 0);
        if (valread > 0) {
            buffer[valread] = '\0'; // 确保字符串结束符
            printf("Client: %s\n", buffer);
        } else if (valread == 0) {
            printf("Client disconnected.\n");
            break;
        } else {
            perror("recv failed");
            break;
        }
    }
    return NULL;
}

int main() {
    int server_fd;
    struct sockaddr_in Saddr, Caddr;
    socklen_t Caddr_len = sizeof(Caddr);
    char sendBuffer[1024] = {0};

    // 1. 创建套接字
    server_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (server_fd == 0) {
        perror("socket failed");
        exit(EXIT_FAILURE);
    }

    // 2. 绑定 IP 地址和端口
    Saddr.sin_family = AF_INET;
    Saddr.sin_addr.s_addr = inet_addr("192.168.61.142"); // 本地地址
    Saddr.sin_port = htons(PORT); // 端口号，转换为网络字节序

    if (bind(server_fd, (struct sockaddr *)&Saddr, sizeof(Saddr)) < 0) {
        perror("bind failed");
        close(server_fd);
        exit(EXIT_FAILURE);
    }

    printf("TCP server listening on 192.168.1.100:%d...\n", PORT);

    // 3. 开始监听
    if (listen(server_fd, 4) < 0) {
        perror("listen failed");
        close(server_fd);
        exit(EXIT_FAILURE);
    }

    // 4. 等待连接请求
    client_socket = accept(server_fd, (struct sockaddr *)&Caddr, &Caddr_len);
    if (client_socket < 0) {
        perror("accept failed");
        close(server_fd);
        exit(EXIT_FAILURE);
    }
    printf("Connection accepted from %s:%d\n", inet_ntoa(Caddr.sin_addr), ntohs(Caddr.sin_port));

    // 5. 创建线程用于接收消息
    pthread_t recvThread;
    pthread_create(&recvThread, NULL, receiveMessages, NULL);

    // 6. 发送消息给客户端
    while (1) {
        printf("Server: \n");
        fgets(sendBuffer, sizeof(sendBuffer), stdin); // 从终端读取服务端输入
        send(client_socket, sendBuffer, strlen(sendBuffer), 0); // 发送消息给客户端
    }

    // 7. 关闭连接
    close(client_socket);
    close(server_fd);

    return 0;
}
